package org.googlecode.lightning.search.conf;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;

/**
 * 
 * @author daragon
 * 
 */
public class Configuration implements Iterable<Map.Entry<String, String>> {

	private Properties properties;

	private ClassLoader classLoader;
	{
		classLoader = Thread.currentThread().getContextClassLoader();
		if (classLoader == null) {
			classLoader = Configuration.class.getClassLoader();
		}
	}

	public Configuration() {
		this(true);
	}

	public Configuration(boolean loadDefaults) {

		if (loadDefaults) {
			loadProps();
		}
	}

	public void set(String name, String value) {
		properties.setProperty(name, value);
	}

	public String get(String name, String defaultValue) {
		return properties.getProperty(name, defaultValue);
	}

	public Iterator<Entry<String, String>> iterator() {
		Map<String, String> result = new HashMap<String, String>();
		for (Map.Entry<Object, Object> entry : loadProps().entrySet()) {
			if (entry.getKey() instanceof String
					&& entry.getValue() instanceof String) {
				result.put((String) entry.getKey(), (String) entry.getValue());
			}
		}
		return result.entrySet().iterator();
	}

	private Properties loadProps()  {
		if (properties == null) {
			properties = new Properties();
			try {
				loadResource(properties);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return properties;
	}

	private void loadResource(Properties properties) throws IOException {
		InputStream inStream = classLoader
				.getResourceAsStream("index-config.properties");
		properties.load(inStream);
	}
	
}
